package com.mdd.front.controller;

import com.mdd.common.aop.NotLogin;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.message.Message;
import com.mdd.common.util.RedisUtils;
import com.mdd.common.util.StringUtils;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.IMessageService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.member.MemberSearchValidate;
import com.mdd.front.vo.message.MessageListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/message")
@Api(tags = "留言")
public class MessageController {

    @Resource
    private IMessageService messageService;

    @NotLogin
    @GetMapping("/lists")
    @ApiOperation(value="赛事列列表")
    public AjaxResult<PageResult<MessageListVo>> list(@Validated PageValidate pageValidate,
                                                      @Validated MemberSearchValidate valicate) {
        Integer userId = LikeFrontThreadLocal.getUserId();
        valicate.setUserId(userId);
        PageResult<MessageListVo> list = messageService.listMessage(pageValidate, valicate);
        return AjaxResult.success(list);
    }

    @PostMapping
    public AjaxResult addMessage(@RequestBody Message message) {
        Integer userId = LikeFrontThreadLocal.getUserId();
        Object nickname = LikeFrontThreadLocal.get("nickname");
        message.setCreateId(userId);
        message.setCreateName(nickname.toString());
        message.setCreateTime(System.currentTimeMillis() / 1000);
        messageService.saveMessage(message);
        return AjaxResult.success();
    }

    @GetMapping("/like/{id}")
    public AjaxResult oneLike(@PathVariable("id") Integer id){
        Integer userId = LikeFrontThreadLocal.getUserId();
        String key = "message:like:"+id+":"+userId;
        Object code = RedisUtils.get(key);

        if (StringUtils.isNull(code) || StringUtils.isEmpty(code.toString())) {
            RedisUtils.set(key, 1, 86400);//使用 Redis 缓存用户点赞记录
            return AjaxResult.success(messageService.oneLike(id));//设置 24 小时过期时间，允许用户次日重新操作
        }
        return AjaxResult.success(messageService.getById(id));
    }

    @GetMapping("/dislike/{id}")
    public AjaxResult disLike(@PathVariable("id") Integer id){
        Integer userId = LikeFrontThreadLocal.getUserId();
        String key = "message:disLike:"+id+":"+userId;
        Object code = RedisUtils.get(key);

        if (StringUtils.isNull(code) || StringUtils.isEmpty(code.toString())) {
            RedisUtils.set(key, 1, 86400);
            return AjaxResult.success(messageService.disLike(id));
        }
        return AjaxResult.success(messageService.getById(id));
    }

}
